<?php

namespace app\socket\controller;
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */

use think\worker\Server;
use Workerman\Lib\Timer;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class WxLogin extends Server
{
    protected $host = '0.0.0.0';
    protected $port = 3315;
    protected $protocol = 'websocket';
    protected $option = [
        'count'   => 4, //设置进程数，默认为4，根据自己的需要和服务器配置合理设置，一般设置进程数为CPU核数的1倍-3倍
        'name'    => 'think',
//        'transport' => 'ssl',   //设置transport开启ssl，启用wss://
    ];
    protected $context = [
//        'ssl' => array(
//            // 请使用绝对路径
//            'local_cert'                 => __DIR__ . '/../../../fucity.cn.pem', // 也可以是crt文件
//            'local_pk'                   => __DIR__ . '/../../../fucity.cn.key',
//            'verify_peer'                => false,
//            // 'allow_self_signed' => true, //如果是自签名证书需要开启此选项
//        ),
    ];
    /**
     * 当客户端连接时触发
     */
    public static function onConnect($connection): void
    {
        // 向当前client_id发送数据
        $connection->client_id = uniqid().time();
        $connection->send(success([
            'token' => $connection->client_id,
        ],'连接成功！'));
    }

   /**
    * 当客户端发来消息时触发
    */
   public static function onMessage($connection, $message)
   {
   }
   
   /**
    * 当用户断开连接时触发
    */
   public static function onClose($connection): void
   {
   }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker): void
    {
        //心跳
        Timer::add(1, function() use ($worker) {
            foreach ($worker->connections as $connection) {
                $openid = cache('WxLogin_'.$connection->client_id);
                if (!$openid) continue;
                $connection->send(success([
                    'is_login' => 1,
                ],'登录成功！'));
            }
        });
    }
}
